package test6;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class Demo9 {

    // 记录所有子树
    static HashMap<String, Integer> memo = new HashMap<>();
    // 记录重复的子树根节点
    static List<TreeNode> res = new LinkedList<>();

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(4);
        root.right = new TreeNode(3);
        root.right.left = new TreeNode(2);
        root.right.left.left = new TreeNode(4);
        root.right.right = new TreeNode(4);

        String traverse = traverse(root);
        System.out.println(traverse);
        System.out.println(res);
    }

    static String traverse(TreeNode root) {
        // 对于空节点，可以用一个特殊字符表示
        if (root == null) {
            return "#";
        }
        // 将左右子树序列化成字符串
        String left = traverse(root.left);
        String right = traverse(root.right);
        // 后序遍历代码位置
        // 左右子树加上自己，就是以自己为根的二叉树序列化结果
        String subTree = new StringBuilder(left).append(",").append(right).append(",").append(root.val).toString();
        Integer freq = memo.getOrDefault(subTree, 0);
        if (freq == 1) {
            res.add(root);
        }
        memo.put(subTree, freq + 1);
        return subTree;
    }
}
